

function factory (UserModel) {
  return {
    intro: function (req, res) {
      //  修改简介
      //  body: {userId: _id, newIntro: 'dg....'}
      var body = req.body
      UserModel.update({_id: body.userId}, {$set: {intro: body.newIntro}}, function (err, user) {
        res.send('1')
      })
    },
    password: function (req, res) {
      //  修改密码
      //  body: {userId:_id,oldPassword: oldPassword, newPassword: newPassword}
      //  当前密码错误返回 0
      var body = req.body
      UserModel.findOne({_id: body.userId}, function (err, user) {
        if (user.password !== body.oldPassword) {
          res.send('0')
        }else {
          user.password = body.newPassword
          user.save(function (err, user) {
            res.send('1')
          })
        }
      })
    },
    email: function (req, res) {
      //  改绑邮箱
      //  body: {userId: _id, newEmail: newEmail, authCode: authCode}
      //  验证码错误返回
      var body = req.body
      UserModel.findOne({_id: body.userId}, function (err, user) {
        if (req.session.authCode !== body.authCode) {
          res.send('0')
        }else {
          user.email = body.newEmail
          user.save(function (err, user) {
            res.send('1')
          })
        }
      })
    },
    care: function (req, res) {
      //  关注他
      //  body: {handlerId: userId, targeterId: targetId}
      //  功能： handler care字段添加targeter的id；targeter的 fans字段添加handler的id
      var body = req.body
      UserModel.findOne({_id: body.handlerId}, function (err, handler) {
        if (handler.care.indexOf(body.targeterId) > -1) {
          res.send('0')
        }else {
          handler.care.push(body.targeterId)
          handler.save(function (err, h) {
            UserModel.findOne({_id: body.targeterId}, function (err, targeter) {
              targeter.fans.push(handler._id)
              targeter.save(function (err, t) {
                res.send('1')
              })
            })
          })
        }
      })
    },
    cancelCare: function (req, res) {
      //  取消关注
      //  与关注相反
      var body = req.body
      UserModel.findOne({_id: body.handlerId}, function (err, handler) {
          handler.care.splice(handler.care.indexOf(body.targeterId), 1)
          handler.save(function (err, h) {
            UserModel.findOne({_id: body.targeterId}, function (err, targeter) {
              targeter.fans.splice(targeter.fans.indexOf(handler._id), 1)
              targeter.save(function (err, t) {
                res.send('1')
              })
            })
          })

      })
    }

  }
}

module.exports = factory